package models

import (
	"LoveU/utils"
	"strconv"
	"time"
	
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

// 登录dao操作
// 状态码表示如下
// utils.OK：登陆成功
// utils.LOGIN_PWDWRONG：用户密码错误
// utils.LOGIN_USRWRONG：用户不存在
func Login(name, passwd string) int64 {
	o := orm.NewOrm()
	qs := o.QueryTable("user")
	user := new(User)
	err := qs.Filter("name", name).One(user)
	if err != nil {
		//用户不存在
		if user.Name == "" {
			return utils.LOGIN_USRWRONG
		}
	} else {
		//密码不正确
		if user.Password != passwd {
			return utils.LOGIN_PWDWRONG
		}
	}
	return utils.OK
}

// 获取一个用户对象
// 返回nil说明不正确的登录状态
func GetUser(name, passwd string) (int64,*User) {
	o := orm.NewOrm()
	qs := o.QueryTable("user")
	user := new(User)
	err := qs.Filter("name", name).Filter("frozen", false).One(user)
	if err != nil {
		//用户不存在
		if user.Name == "" {
			beego.Error("用户不存在")
			return utils.LOGIN_USRWRONG,nil
		}
	} else {
		//密码不正确
		if user.Password != passwd {
			beego.Error(user.Password, passwd)
			beego.Error("密码不正确")
			return utils.LOGIN_PWDWRONG,nil
		}
		if user.Frozen==true {
			return utils.USER_FROZEN,nil
		}
	}
	return utils.LOGIN_OK,user
}

//通过ID获取用户对象
func GetUser2(userid int64) *User {
	o := orm.NewOrm()
	qs := o.QueryTable("user")
	user := new(User)
	err := qs.Filter("id", userid).One(user)
	if err != nil {
		//用户不存在
		if user.Name == "" {
			beego.Error("用户不存在")
			return nil
		}
	}
	return user
}

//获得用户的详细信息（userid：用户ID）
func GetUserInfo(userid int64) *UserInfoReturn {
	o := orm.NewOrm()
	qs := o.QueryTable("pinformation")
	pInfo := new(Pinformation)
	err := qs.Filter("userid", userid).One(pInfo)
	user := GetUser2(userid)
	if err != nil || user==nil {
		//用户不存在
		return nil
	}
	status,areaInfo := GetAreaById(pInfo.Area)
	var areaName string
	if status==utils.AREA_CODE_OK {
		areaResult := new(AreaResult)
		GetAreaNames(areaResult,areaInfo)
		areaName = areaResult.Province + areaResult.Country
	} else if status==utils.AREA_CODE_NOT_FOUND{
		areaName = "海外"
	} else {
		areaName = ""
	}
	returns := &UserInfoReturn{
		Pinformation: *pInfo,
		Phone: user.Phone,
		AreaName: areaName,
	}
	return returns
}

// 获取用户的ID
func GetUserId(name, passwd string) int64 {
	_,user := GetUser(name, passwd)
	if user != nil {
		return user.Id
	}
	return -1
}

// 用户注册，仅需要填用户名，密码和手机号
func Register(name, phone, passwd string) int64 {
	//检查用户名重复
	status := CheckName(name)
	if status == utils.REG_NAME_EXISTS {
		return utils.REG_NAME_EXISTS
	}
	//检查手机号重复
	status = CheckPhone(phone)
	if status == utils.REG_PHONE_EXISTS {
		return utils.REG_PHONE_EXISTS
	}
	user := &User{
		Name:     name,
		Phone:    phone,
		Password: passwd,
	}
	o := orm.NewOrm()
	_, err := o.Insert(user)
	if err != nil {
		return 10001
	}
	return 10
}

// 注册完善信息
// 返回值信息：
// utils.UNKNOWN_ERROR：
// utils.OK：
func Register2(userid, areaid int64, gentle, birthday, job, salary, havekids, parentsalive, maritallstatus, emtion, hobby, requir, avatar string) int64 {
	o := orm.NewOrm()
	qs := o.QueryTable("pinformation")

	// 已移除“是否已填写信息”的检测。现在同时支持修改信息。
	// 将时间的字符串转换成时间类型
	birthday_date, err0 := String2Time(birthday)
	salary_float, err1 := strconv.ParseFloat(salary, 64)
	havakids_bool, err2 := strconv.ParseBool(havekids)
	parentsalive_bool, err3 := strconv.ParseBool(parentsalive)

	if err0 != nil || err1 != nil || err2 != nil || err3 != nil {
		return utils.ARGUMENT_DENIED
	}

	userInfo := new(Pinformation)
	err4 := qs.Filter("userid", userid).One(userInfo)
	if err4 == orm.ErrNoRows {
		pinformation := &Pinformation{
			Vip:            false,
			Birthday:       birthday_date,
			Area:           areaid,
			Gentle:			getGentleInt(gentle),
			Job:            job,
			Salary:         salary_float,
			HaveKids:       havakids_bool,
			Parentsalive:   parentsalive_bool,
			Maritallstatus: maritallstatus,
			Emotion:        emtion,
			Hobby:          hobby,
			Requir:         requir,
			Userid:         userid,
			Avatar:         avatar,
		}
		_, err := o.Insert(pinformation)
		if err != nil {
			beego.Error("Database error when creating Pinformation")
			return utils.UNKNOWN_ERROR
		}
	} else if err4 == nil {
		userInfo.Area = areaid
		userInfo.Avatar = avatar
		userInfo.Birthday = birthday_date
		userInfo.Emotion = emtion
		userInfo.Gentle = getGentleInt(gentle)
		userInfo.HaveKids = havakids_bool
		userInfo.Hobby = hobby
		userInfo.Job = job
		userInfo.Maritallstatus = maritallstatus
		userInfo.Parentsalive = parentsalive_bool
		userInfo.Requir = requir
		userInfo.Salary = salary_float
		_, err5 := o.Update(userInfo)
		if err5 != nil {
			beego.Error("Database error when modifing Pinformation")
			return utils.UNKNOWN_ERROR
		}
	} else {
		beego.Error(err4.Error())
		return utils.UNKNOWN_ERROR
	}

	return utils.OK
}

// 用户注册后，自动填写默认的详细信息（忽略数据库错误）
func RegisterDefault(userId int64) {
	var area int64 = 1
	//默认“北京市 北京市 东城区”
	avatar := ""
	birthday := "1970-01-01"
	emotion := ""
	gentle := "0"
	haveKids := "f"
	hobby := ""
	job := "自由职业"
	mStatus := "暂缺"
	pAlive := "t"
	requir := ""
	salary := "0.0"
	Register2(userId,area,gentle,birthday,job,salary,haveKids,pAlive,mStatus,emotion,hobby,requir,avatar)
}

// 通过userid获取用户对象
func getUser(userid int64) *User {
	o := orm.NewOrm()
	qs := o.QueryTable("user")
	user := new(User)
	err := qs.Filter("Id", userid).One(user)
	if err != nil {
		return nil
	}
	return user
}

//通过用户名获取用户
func getUserByname(name string) *User {
	o := orm.NewOrm()
	qs := o.QueryTable("user")
	user := new(User)
	err := qs.Filter("name", name).One(user)
	if err != nil {
		return nil
	}
	return user
}

//通过用户名获取ID
func getUserIDByname(name string) int64 {
	o := orm.NewOrm()
	qs := o.QueryTable("user")
	user := new(User)
	err := qs.Filter("name", name).One(user)
	if err != nil {
		return -1
	}
	return user.Id
}

func getUserAvatar(userid int64) string {
	o := orm.NewOrm()
	qs := o.QueryTable("pinformation")
	pInfo := new(Pinformation)
	err := qs.Filter("userid", userid).One(pInfo)
	if err != nil {
		return ""
	}
	return pInfo.Avatar
}

// 提交VIP申请
// 1.检查用户是否是VIP，检查用户详情表
// 2.如果是VIP拒绝申请
// 3.不是VIP，检查是否成功申请且等待审核
// 4.如果申请成功，还没有审核，返回等待
// 5.申请成功，被拒绝，返回拒绝理由
// 6.被拒绝，则将该被申请设置标志
func RequestVIP(userid int64, url1, url2, url3 string) (string, int64) {
	o := orm.NewOrm()
	// qs := o.QueryTable("pinformation")
	// num, err := qs.Filter("userid", userid).Filter("vip", true).Count()
	// if num != 0 {
	// 	return "用户已经是vip用户", utils.VIP_USERR
	// }
	// qs = o.QueryTable("viprequest")
	// num, err = qs.Filter("userid", userid).Filter("agree", 0).Count()
	// if num != 0 {
	// 	return "已经发送VIP申请，待审核", utils.VIP_REQUEST_SENDED
	// }

	// num, err = qs.Filter("userid", userid).Filter("agree", 2).Filter("Useless", false).Count()
	// if num != 0 {
	// 	vrequest := new(Viprequest)
	// 	err = qs.Filter("userid", userid).Filter("agree", 2).Filter("Useless", false).One(vrequest)
	// 	if err != nil {
	// 		return "未知错误238", utils.UNKNOWN_ERROR
	// 	}
	// 	vrequest.Useless = true
	// 	return vrequest.Refusereason, utils.VIP_REJECT
	// }
	vipResult, status := CheckVIP(userid)
	if status != utils.OK {
		return vipResult, status
	}
	request := &Viprequest{
		Userid:  userid,
		Picurl1: url1,
		Picurl2: url2,
		Picurl3: url3,
	}
	_, err := o.Insert(request)
	if err != nil {
		return "未知错误251", utils.UNKNOWN_ERROR
	}
	return "success", utils.OK
}

// func GetVIPResult(userid int64) int64 {
// 	o := orm.NewOrm()
// 	qs := o.QueryTable("viprequest")
// 	num, err := qs.Filter("userid", userid).Count()
// 	if err != nil {
// 		return utils.UNKNOWN_ERROR
// 	}
// 	if num == 0 {
// 		return utils.USER_REALINFO_NOT_FOUND
// 	}
// 	num, err = qs.Filter("userid", userid).Filter("agree", 1).Count()
// 	if err != nil {
// 		return utils.UNKNOWN_ERROR
// 	}
// }

func CheckVIP(userid int64) (string, int64) {
	o := orm.NewOrm()
	qs := o.QueryTable("pinformation")
	num, err := qs.Filter("userid", userid).Filter("vip", true).Count()
	if num != 0 {
		return "用户已经是vip用户", utils.VIP_USERR
	}
	qs = o.QueryTable("viprequest")
	num, err = qs.Filter("userid", userid).Filter("agree", 0).Count()
	if num != 0 {
		return "已经发送VIP申请，待审核", utils.VIP_REQUEST_SENDED
	}

	num, err = qs.Filter("userid", userid).Filter("agree", 2).Filter("Useless", false).Count()
	if num != 0 {
		vrequest := new(Viprequest)
		err = qs.Filter("userid", userid).Filter("agree", 2).Filter("Useless", false).One(vrequest)
		if err != nil {
			return "未知错误238", utils.UNKNOWN_ERROR
		}
		vrequest.Useless = true
		return vrequest.Refusereason, utils.VIP_REJECT
	}
	return "success", utils.OK
}

//获取用户信息
func getPersonInfor(userid int64) *Pinformation {
	o := orm.NewOrm()
	qs := o.QueryTable("Pinformation")
	pInfo := new(Pinformation)
	err := qs.Filter("userid", userid).One(pInfo)
	if err == orm.ErrNoRows && err != nil {
		return nil
	}
	return pInfo
}

//修改签名
func ModifyAutograph(userid int64, autograph string) bool {
	o := orm.NewOrm()
	pInfo := getPersonInfor(userid)
	if pInfo == nil {
		return false
	}
	pInfo.Autograph = autograph
	_, err := o.Update(pInfo)
	if err != nil {
		return false
	}
	return true
}

//修改性别
func ModifyGentle(userid int64, gentle int64) bool {
	o := orm.NewOrm()
	pInfo := getPersonInfor(userid)
	if pInfo == nil {
		return false
	}
	pInfo.Gentle = gentle
	_, err := o.Update(pInfo)
	if err != nil {
		return false
	}
	return true
}

// 修改生日
func ModifyBirthday(userid int64, birthday time.Time) bool {
	o := orm.NewOrm()
	pInfo := getPersonInfor(userid)
	if pInfo == nil {
		return false
	}
	pInfo.Birthday = birthday
	_, err := o.Update(pInfo)
	if err != nil {
		return false
	}
	return true
}

// 修改地区
func ModifyArea(userid int64, area int64) bool {
	o := orm.NewOrm()
	pInfo := getPersonInfor(userid)
	if pInfo == nil {
		return false
	}
	pInfo.Area = area
	_, err := o.Update(pInfo)
	if err != nil {
		return false
	}
	return true
}

// 修改职业
func ModifyJob(userid int64, job string) bool {
	o := orm.NewOrm()
	pInfo := getPersonInfor(userid)
	if pInfo == nil {
		return false
	}
	pInfo.Job = job
	_, err := o.Update(pInfo)
	if err != nil {
		return false
	}
	return true
}

// 修改收入
func ModifySalary(userid int64, salary float64) bool {
	o := orm.NewOrm()
	pInfo := getPersonInfor(userid)
	if pInfo == nil {
		return false
	}
	pInfo.Salary = salary
	_, err := o.Update(pInfo)
	if err != nil {
		return false
	}
	return true
}

// 是否有孩子
func ModifyHaveKids(userid int64, havekids bool) bool {
	o := orm.NewOrm()
	pInfo := getPersonInfor(userid)
	if pInfo == nil {
		return false
	}
	pInfo.HaveKids = havekids
	_, err := o.Update(pInfo)
	if err != nil {
		return false
	}
	return true
}

// 父母是否健在
func ModifyParentsalive(userid int64, parentsalive bool) bool {
	o := orm.NewOrm()
	pInfo := getPersonInfor(userid)
	if pInfo == nil {
		return false
	}
	pInfo.Parentsalive = parentsalive
	_, err := o.Update(pInfo)
	if err != nil {
		return false
	}
	return true
}

// 婚姻状况
func ModifyMaritallstatus(userid int64, maritallstatus string) bool {
	o := orm.NewOrm()
	pInfo := getPersonInfor(userid)
	if pInfo == nil {
		return false
	}
	pInfo.Maritallstatus = maritallstatus
	_, err := o.Update(pInfo)
	if err != nil {
		return false
	}
	return true
}

// 情感信息
func ModifyEmotion(userid int64, emotion string) bool {
	o := orm.NewOrm()
	pInfo := getPersonInfor(userid)
	if pInfo == nil {
		return false
	}
	pInfo.Emotion = emotion
	_, err := o.Update(pInfo)
	if err != nil {
		return false
	}
	return true
}

// 修改兴趣爱好
func ModifyHobby(userid int64, hobby string) bool {
	o := orm.NewOrm()
	pInfo := getPersonInfor(userid)
	if pInfo == nil {
		return false
	}
	pInfo.Hobby = hobby
	_, err := o.Update(pInfo)
	if err != nil {
		return false
	}
	return true
}

// 修改求偶需求
func ModifyRequir(userid int64, requir string) bool {
	o := orm.NewOrm()
	pInfo := getPersonInfor(userid)
	if pInfo == nil {
		return false
	}
	pInfo.Requir = requir
	_, err := o.Update(pInfo)
	if err != nil {
		return false
	}
	return true
}
